// packageStore/pages/distribution/card/index.js
import {api,util} from '../../../js/util';
import BasePage from '../../../js/common/base-page';
import {config,share} from "../../../js/modules/gloab";
import authorize from '../../../js/modules/authorize.js'
import drawQrcode from '../../../js/common/weapp.qrcode.min.js'
import {
  pagesInfo
} from '../../../js/router';
import {
  profile
} from "../../../js/modules/store.js";

const app = getApp()
BasePage({
  validateLogin:false,
  /**
   * 页面的初始数据
   */
  data: {
    pic:"",
    imgDomain: api.imgDomain,
    name:'',
    siteName:'',
    pageBg:'',
    downlogo:'',
    canvasId:'canvas',
    qrCode:'',
    showBtn:false,
    isH5:false,     //是否从内嵌的H5页面转入
    h5Info:{}        //从H5转入后的分享信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({title: '加载中'})
    var that=this;
    let currentRoute;
    if(options && options.resource == 'H5'){
      let obj = {};
      obj.flag = options.flag;
      obj.id = options.id;
      obj.userId = options.userId;
      this.setData({
        name:options.name,
        siteName:options.siteName,
        isH5:true,
        h5Info:obj
      })
      currentRoute={
        urlWithArgs:options.flag+'_' + options.id + '_' + options.userId,
        url:pagesInfo.distributionInvite.url
      };
    }else{
      var storeInfo = authorize.getEntity();
      this.setData({
        name:storeInfo.role.Name,
        pic:storeInfo.role.Logo
      })
      this.getWholesaleConfig()
      currentRoute={
        urlWithArgs:storeInfo.fkFlag+'_' + storeInfo.fkId + '_' + storeInfo.manager.ManagerId,
        url:pagesInfo.distributionInvite.url
      };
    }
    console.log(currentRoute,'========code');
    profile.load_wx_qrcode(currentRoute,function (content){
      if (content!=""){
        var url = "data:image/png;base64," + content;
        that.setData({
          preQR: url
        })
        util.base64src(url, function (res) {
          url = res;
          that.setData({
            qrCode: url
          },()=>{
            that.drawPicture()
          });
        });
      }else{
        that.setData({
          showPosterShadow:false
        },function(){
          util.tips("未能生成小程序码");
          return;
        })
      }

    });
    this.getShareInfo();
  },
  savePic:function(){
    //this.drawPicture()]
    this.saveShareImg()
  },
    //绘制海报
    drawPicture:function(){
      let that = this;
      //获取设备信息高度。计算出其他的高度等
      wx.getSystemInfo({
        success: function (res) {
          // //调整海报清晰度
          that.setData({
            windowWidth: res.windowWidth*2,
            windowHeight: res.windowHeight*2,
            canvasId: "canvas"
          });
          res.windowWidth = res.windowWidth*2;
          res.windowHeight = res.windowHeight * 2;
          that.initData(res);
        }
      });
  
    },
  initData:function(res){
    let that = this;
    let interval=40,start=15;
    that.setData({
      imgDomain: api.imgDomain,
      boxWidth: res.windowWidth, //分享图片box宽度
      boxheight: res.windowHeight, //分享图片box高度
      boxPageY: 0, //boxY轴位置
      squareY:res.windowHeight*0.2,//白色矩形Y轴
      squareX:res.windowWidth*0.1,//白色矩形X轴
      codeWidth: res.windowWidth*0.45, //二维码图片宽度
      codeHeight: res.windowWidth*0.45, //二维码图片高度
      codePageY: res.windowHeight*0.45, //二维码Y轴位置
      codePageX:res.windowWidth*0.5-res.windowWidth*0.45/2,//二维码X轴位置
      title1PageY: res.windowHeight*0.2+res.windowWidth * 0.1+start, //标题1Y轴位置
      title2PageY: res.windowHeight*0.2+res.windowWidth * 0.1+start+interval*1, //标题2Y轴位置
      title3PageY: res.windowHeight*0.2+res.windowWidth * 0.1+start+interval*2, //标题3Y轴位置
      title4PageY: res.windowHeight*0.2+res.windowWidth * 0.1+start+interval*3, //标题4Y轴位置
      tipsPageY: res.windowHeight*0.45+res.windowWidth*0.45+20,//扫一扫提示
      smallcircularY:res.windowHeight*0.2+res.windowWidth * 0.1+80+res.windowWidth * 0.05,//小半圆
      smallcircularWidth:res.windowWidth * 0.05,//小半圆宽度
      logo:that.data.pic,
      logoWidth: res.windowWidth * 0.2,
      logoY:res.windowHeight*0.2-res.windowWidth * 0.1,
      logoX:res.windowWidth * 0.5-res.windowWidth * 0.1,
    });
    that.createNewImg()
  },
    //画矩形，也是整块画布的大小，宽度是屏幕宽度，高度根据内容多少来动态设置。
    drawSquare: function (ctx, height) {
      let that = this;
      ctx.rect(
        0,
        0,
        that.data.boxWidth,
        height
      );
      ctx.setFillStyle(api.titleColor||"#e56b14");
      ctx.fill();
    },
    drawSquare2: function (ctx, height) {
      let that = this;
      ctx.setFillStyle("#fff");
      this.roundRect(ctx,that.data.squareX,that.data.squareY,(that.data.boxWidth*0.8),(height*0.6),10)
    },

/**
 * 绘制圆角矩形
 * @param {Object} ctx - canvas组件的绘图上下文
 * @param {Number} x - 矩形的x坐标
 * @param {Number} y - 矩形的y坐标
 * @param {Number} w - 矩形的宽度
 * @param {Number} h - 矩形的高度
 * @param {Number} r - 矩形的圆角半径
 * @param {String} [c = 'transparent'] - 矩形的填充色
 */
roundRect(ctx, x, y, w, h, r, c = '#fff') {
  if (w < 2 * r) { r = w / 2; }
  if (h < 2 * r) { r = h / 2; }

  ctx.beginPath();
  ctx.fillStyle = c;

  ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + w - r, y);
  ctx.lineTo(x + w, y + r);

  ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
  ctx.lineTo(x + w, y + h - r);
  ctx.lineTo(x + w - r, y + h);

  ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
  ctx.lineTo(x + r, y + h);
  ctx.lineTo(x, y + h - r);

  ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
  ctx.lineTo(x, y + r);
  ctx.lineTo(x + r, y);

  ctx.fill();
  ctx.closePath();
},
    drawLogo:function(ctx){
      let that = this;
      ctx.save();
          //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
          ctx.arc(that.data.logoWidth / 2 + that.data.logoX, that.data.logoWidth / 2 + that.data.logoY, that.data.logoWidth / 2, 0, Math.PI * 2, false);
          ctx.clip();//画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
          ctx.drawImage(that.data.downlogo, that.data.logoX, that.data.logoY, that.data.logoWidth, that.data.logoWidth); // 推进去图片，必须是https图片
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    },
    drawFont:function(ctx){
      ctx.font = "20px Arial";
      ctx.fillStyle = "#bbb";
      let infoText = this.data.name
      let nameWidth = ctx.measureText(infoText).width
      ctx.fillStyle = "#ff4242";
      ctx.fillText(this.data.name, (this.data.boxWidth - nameWidth) / 2 , this.data.title1PageY);

      ctx.fillStyle = "#666";
      let mallInfoWidth = ctx.measureText('向您推荐').width
      ctx.fillText('向您推荐', (this.data.boxWidth - mallInfoWidth) / 2, this.data.title2PageY);

      ctx.fillStyle = "black";
      let siteWidth = ctx.measureText(this.data.siteName).width
      ctx.fillText(this.data.siteName, (this.data.boxWidth - siteWidth) / 2, this.data.title3PageY);

    },
    drawSmallCircular:function(ctx){
      ctx.beginPath();
      ctx.arc(this.data.squareX, this.data.smallcircularWidth / 2 + this.data.smallcircularY, this.data.smallcircularWidth / 2, 0, 2 * Math.PI);
      ctx.fillStyle = api.titleColor||"#e56b14";
      ctx.fill();
      ctx.closePath();

      ctx.beginPath();
      ctx.arc(this.data.squareX + this.data.boxWidth*0.8, this.data.smallcircularWidth / 2 + this.data.smallcircularY, this.data.smallcircularWidth / 2, 0, 2 * Math.PI);
      ctx.fillStyle = api.titleColor||"#e56b14";
      ctx.fill();
      ctx.closePath();
    },
    createNewImg: function () {
      let that = this;
      let ctx = wx.createCanvasContext(that.data.canvasId);
      let contentHeight = that.data.boxheight;
      that.drawSquare(ctx, contentHeight);
      that.drawSquare2(ctx, contentHeight);
      //logo
      // that.drawLogo(ctx)
      // 填充文字
      that.drawFont(ctx)
      //小圆圈
      that.drawSmallCircular(ctx)
      // 填充二维码
      ctx.drawImage(
        that.data.qrCode,
        that.data.codePageX,
        that.data.codePageY,
        that.data.codeWidth,
        that.data.codeHeight
      );
      ctx.setFillStyle("#bbb");
      ctx.font = "20px Arial";
      let codeWidth = ctx.measureText('扫一扫/长按识别，即享订货专属服务').width
      ctx.fillText('扫一扫/长按识别，即享订货专属服务', (this.data.boxWidth - codeWidth) / 2, this.data.tipsPageY);
      setTimeout(() => {
        ctx.draw(false,function(){
          wx.canvasToTempFilePath({
            canvasId: 'canvas',
            success: function (res) {
              wx.hideLoading();
              var tempFilePath = res.tempFilePath;
              that.setData({
                tempFilePath,
                showBtn:true
              })
            },
            fail:function(err){
              console.info(err);
            }
          });
        }); //绘制到canvas
      }, 800);
      setTimeout(function (){wx.hideLoading()},3000)
    },
      //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    wx.saveImageToPhotosAlbum({
      filePath: that.data.tempFilePath,
      success(res) {
        wx.hideLoading();
        // utils.aiCardActionRecord(19);
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) { }
          },
          fail: function (res) { }
        })
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: "保存失败",
          icon: 'none',
          duration: 2000
        })
      }
    })
  } ,
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      function (model) {
        that.setData({
          siteName:model.SiteName
        });
      });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      pageBg: api.titleColor||"#e56b14"
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 获取分享信息
   */
  getShareInfo:function(){
    let that = this;
    let {isH5,h5Info} = that.data;
    let param = {
        Proprietor:app.dns.proprietor,
        ProprietorId:app.dns.proprietorId,
        Type:'card'
    }
    if(isH5){
      param.FKFlag = h5Info.flag;
      param.FKId = h5Info.id;
    }
    share.getinfo(param,isH5,function(res){
        let shareObj = {};
        shareObj.title = res.Title || "邀请加入";
        shareObj.img = res.ImgSrc!='' ? api.imgDomain+res.ImgSrc : '';
        that.setData({
            shareObj:shareObj
        })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let {shareObj,isH5,h5Info} = this.data;
    let path;
    if(isH5){
      path= pagesInfo.distributionInvite.url+"?scene="+h5Info.flag+"_"+h5Info.id+"_"+h5Info.userId;
    }else{
      var storeInfo = authorize.getEntity();
      path= pagesInfo.distributionInvite.url+"?scene="+storeInfo.fkFlag+"_"+storeInfo.fkId+"_"+storeInfo.manager.ManagerId;
    }
    return {
      title: shareObj.title,
      imageUrl: shareObj.img,
      path: path
    }
  }
})